package com.sky.service.admin.impl;

import com.sky.dto.DishDTO;
import com.sky.mapper.admin.DishFlavorMapper;
import com.sky.mapper.admin.DishMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.DishFlavor;
import com.sky.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description DishServiceImpl
 * @Author shejunlian
 * @Date 2024-07-23
 */
@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    /**
     * 新增菜品和对应的口味
     * @param dishDTO
     * @return
     */
    @Override
    @Transactional
    public void addCuisineFlavor(DishDTO dishDTO) {
        //1.创建空菜品的实体类
        Dish dish = new Dish();
        //2.将 DishDTO 拷贝到空实体类当中 dish
        BeanUtils.copyProperties(dishDTO, dish);

        //3.向菜品表插入一条数据
        dishMapper.insert(dish);

        //6.获取insert语句生成的主键值
        Long id = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        //4.判断flavors 不等于空 同时, flavors数量 > 0
        if (flavors != null && flavors.size() > 0) {
            //7.遍历flavors
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(id);
            });

            //5.向口味表插入n条数据(批量插入)
            dishFlavorMapper.insertBatch(flavors);

        }

    }
}
